<?php

namespace app\api\controller\cms;
use app\api\model\LinMenu;
use app\api\model\UserMenu;
use app\api\service\token\LoginToken;
use LinCmsTp5\admin\model\LinUser;
use think\Db;
use think\Exception;
use think\Request;

class Menu
{

    /**
     * @auth('创建管理后台菜单','管理员','hidden')
     * @param Request $request
     * @return \think\response\Json
     */
    public function createMenu(Request $request){
        $params = $request->post();
        $menu = LinMenu::field("*");
        if (!empty($params['pid'])){
            $menu->where("pid",$params['pid']);
        }
        $info = $menu->where("title",$params['title'])->findOrEmpty();
        if (!$info->isEmpty()){
            throw new Exception([
                'msg' => '菜单名称已存在',
                'error_code' => 20001
            ]);
        }
        LinMenu::create($params);
        return writeJson(201, '', '菜单创建成功');
    }


    /**
     * @auth('更新管理后台菜单','管理员','hidden')
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateMenu(Request $request){
        $params = $request->param();
        $menu = LinMenu::where("id",$params['id'])->findOrEmpty();
        if ($menu->isEmpty()){
            throw new Exception([
                'msg' => '修改菜单不存在',
                'error_code' => 20001
            ]);
        }
        $menu->save($params);
        return writeJson(201, '', '菜单修改成功');
    }

    /**
     * @auth('删除管理后台菜单','管理员','hidden')
     * @param $id
     * @return \think\response\Json
     */
    public function deleteMenu($id){
        $menu = LinMenu::where("id",$id)->findOrEmpty();
        if ($menu->isEmpty()){
            throw new Exception([
                'msg' => '删除菜单不存在',
                'error_code' => 20001
            ]);
        }
        $menu->delete();
        return writeJson(201, '', '菜单删除成功');
    }


    /**
     * @auth('查询管理后台菜单','管理员','hidden')
     * @param Request $request
     * @param('page','页数','require')
     * @return \think\response\Json
     */
    public function getMenu(Request $request){
        $params = $request->get();
        $count = $params['count']??20;
        $menu = LinMenu::field("id,name,pid,filePath,create_time,update_time,route,title,type,icon,inNav,sort")->order("id desc");
        $menuList = $menu->paginate($count,false,['page'=>$params['page'] + 1])->each(function ($item){
            $item->p_name = LinMenu::where("id",$item->pid)->value("title");
        });
        return writeJson(201, $menuList, '数据列表');
    }

//    /**
//     * @auth('查询管理后台菜单树状图','管理员','hidden')
//     * @return \think\response\Json
//     */
    public function getMenuStructure(){
        $menu = LinMenu::field("id,name,pid,filePath,route,title,type,inNav,icon")->order("sort desc")->select()->toArray();
        $tree = $this->getTree($menu, 0);
        return writeJson(201, $tree, '数据列表');
    }

    /**
     * @auth('查询管理后台菜单指定','管理员','hidden')
     * @param $id
     * @return \think\response\Json
     */
    public function getMenuOne($id){
        $menu = LinMenu::field("id,name,pid,filePath,route,title,type,inNav,icon")->where("id",$id)->find();

        return writeJson(201, $menu, '数据列表');
    }

    /**
     * @auth('查询管理后台菜单指定','管理员','hidden')
     * @param $groupId
     * @return \think\response\Json
     */
    public function getAppointMenu($groupId){
        $menu = UserMenu::where("group_id",$groupId)->json(['menu_id'])->find();

        return writeJson(201, $menu, '数据列表');
    }

    /**
     * @auth('用户菜单配置变更','管理员','hidden')
     * @param Request $request
     * @return \think\response\Json
     */
    public function setAppointMenu(Request $request){
        $params = $request->post();
        $menu = UserMenu::where("group_id",$params['group_id'])->findOrEmpty();
        DB::startTrans();
        try {
            if ($menu->isEmpty()){
                UserMenu::create($params);
            }else{
                $menu->save($params);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new Exception([
                'msg' => '菜单配置失败',
                'error_code' => 20003
            ]);
        }
        return writeJson(201, true, '完成');
    }


    public function getAppointUserRoute(){
        $login = LoginToken::getInstance();
        $uid =$login->getCurrentUid();
        $tree = [];
        if ($uid === 1){
            $menu = LinMenu::field("id,name,pid,filePath,route,title,type,inNav,icon")->order("sort desc")->select()->toArray();
        }else{
            $group_id = LinUser::field("group_id")->where("id",$uid)->value("group_id");
            $menus = UserMenu::where("group_id",$group_id)->json(['menu_id'])->find();
            $menu = LinMenu::field("id,name,pid,filePath,route,title,type,inNav,icon")
                ->whereIn("id",$menus['menu_id'])
                ->order("sort desc")->select()->toArray();
        }
        $tree = $this->getTree($menu, 0);
        return writeJson(201, $tree, '数据列表');
    }

    public function getTree($data, $pId)
    {
        $tree = [];
        foreach($data as $k => $v)
        {
            if($v['pid'] == $pId)
            {
                $v['children'] = $this->getTree($data, $v['id']);
                if (empty($v['children'])){
                    unset($v['children']);
                }
                $tree[] = $v;
                unset($data[$k]);
            }
        }
        return $tree;
    }

}
